<script lang='ts' setup>
import { onMounted, ref, watch } from 'vue';
import Vditor from 'vditor';
import 'vditor/dist/index.css';
import Loader from './Loader.vue'
import { appRef } from '@/models/app.ref';
import { Site } from '@/config/base';

const props = withDefaults(defineProps<{ id: string }>(), {})
defineExpose({ setValue })

watch(() => [props.id], () => {
  if (vditor.value) {
    vditor.value!.setValue(appRef.chatWork.currMenu?.article || '');
  } else {
    init();
  }
});

const vditor = ref<Vditor | null>(null);
const loading = ref(false)
onMounted(() => {
  init();
});

function init() {
  try {
    loading.value = true;
    vditor.value = new Vditor('hope-vditor' + props.id, {
      cdn: Site.vditorCdn,
      height: '100%',
      toolbar: [],
      placeholder: '请输入...',
      cache: {
        enable: false,
      },
      input: (value: string) => {
        onSave(value);
      },
      after: () => {
        vditor.value!.setValue(appRef.chatWork.currMenu?.article || '');
        loading.value = false
      }
    });
  } catch (error) {
    console.log(error);
  }
}


/** 保存 */
function onSave(value: string): void {
  appRef.chatWork.setCurrArticle(value);
}

/** 写入值 */
function setValue(value: string): void {
  if (vditor.value!.getValue()) {
    vditor.value!.insertValue(value);
  } else {
    vditor.value!.setValue(value);
  }
}



</script>
<template>
  <div class="md">
    <Loader v-if="loading"></Loader>
    <div :id="'hope-vditor' + props.id" class="vditor"></div>
  </div>
</template>
<style lang='scss'  scoped>
.md {
  width: 50%;
  height: 100%;
  overflow: hidden;
  overflow-y: auto;
  position: relative;
  // box-shadow: #d1d1d1 0 0 7px;
  border-left: 1px solid #d1d1d1;
  padding: 20px;
  background-color: var(--color-bg-1);

  .vditor {
    border: none;
  }

}

::v-deep .vditor-toolbar {
  border: none;
}

::v-deep .vditor-ir {

  pre.vditor-reset,
  pre.vditor-reset:focus {
    background-color: var(--color-bg-1);
    color: var(--color-bg-10);
  }


}

::v-deep .vditor-reset {
  padding: 0 !important;
}
</style>